﻿using log4net;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace MRO.ClientApplication.Util
{
    public class HttpHelper
    {
        public static JsonSerializerSettings JsonSetting = new JsonSerializerSettings
        {
            ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
        };

        #region 原生
        public static string Get(string url)
        {
            using (var client = new WebClient())
            {
                return client.DownloadString(url);
            }
        }

        public static string Post(string url, NameValueCollection data)
        {
            using (WebClient client = new WebClient())
            {
                byte[] responseBytes = client.UploadValues(url, "POST", data);
                return Encoding.UTF8.GetString(responseBytes);
            }
        }

        //public static string PostJson(string url, string json)
        //{
        //    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        //    request.Method = "POST";
        //    request.ContentType = "application/json";
        //    if (json == null)
        //    {
        //        json = string.Empty;
        //    }
        //    request.ContentLength = json.Length;

        //    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        //    {
        //        streamWriter.Write(json);
        //        streamWriter.Flush();
        //        streamWriter.Close();
        //    }

        //    var response = (HttpWebResponse)request.GetResponse();
        //    using (var streamReader = new StreamReader(response.GetResponseStream()))
        //    {
        //        return streamReader.ReadToEnd();
        //    }
        //}

        public static string PutJson(string url, string json)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "PUT";
            request.ContentType = "application/json";
            request.ContentLength = json.Length;

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var response = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                return streamReader.ReadToEnd();
            }
        }

        public static string Delete(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "DELETE";

            var response = (HttpWebResponse)request.GetResponse();
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                return streamReader.ReadToEnd();
            }
        }
        #endregion


        #region 基石部分
        /// <summary>
        /// 基础
        /// </summary>
        /// <param name="request"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string Post(HttpWebRequest request, string json)
        {
            try
            {
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Accept = "application/json";
                if (json == null)
                {
                    json = string.Empty;
                }
                request.ContentLength = json.Length;
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(json);//写入到请求流中
                                             //streamWriter.Flush();//刷新流
                                             //streamWriter.Close();//关闭流
                }
                var response = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    return streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format($"URL={request.RequestUri};Msg={ex.Message}"));
            }

        }

        /// <summary>
        /// 基础 传对象
        /// </summary>
        /// <param name="request"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static string Post(HttpWebRequest request, Object obj)
        {
            try
            {
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Accept = "application/json";
                var json = string.Empty;
                if (obj != null)
                {
                    json = JsonConvert.SerializeObject(obj, Formatting.None, JsonSetting);
                }
                request.ContentLength = json.Length;
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(json);//写入到请求流中
                    //streamWriter.Flush();//刷新流
                    //streamWriter.Close();//关闭流
                }
                var response = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    return streamReader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format($"URL={request.RequestUri};Msg={ex.Message}"));
            }
        }
        /// <summary>
        /// 基础 传对象
        /// </summary>
        /// <param name="request"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Post<T>(HttpWebRequest request, Object obj)
        {
            try
            {
                request.Method = "POST";
                request.ContentType = "application/json";
                request.Accept = "application/json";
                var json = string.Empty;
                if (obj != null)
                {
                    json = JsonConvert.SerializeObject(obj, Formatting.None, JsonSetting);
                }
                request.ContentLength = json.Length;
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(json);//写入到请求流中
                }
                var response = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(response.GetResponseStream()))
                {
                    var res = streamReader.ReadToEnd();
                    return JsonConvert.DeserializeObject<T>(res);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format($"URL={request.RequestUri};Msg={ex.Message}"));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        /// <param name="dicPair"></param>
        /// <returns>请求头增加参数,返回json</returns>
        public static string PostByHeader(string url, object obj, Dictionary<string, string> dicPair)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                if (dicPair != null)
                {
                    foreach (var pair in dicPair)
                    {
                        request.Headers.Add(pair.Key, pair.Value);
                    }
                }
                return Post(request, obj);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 请求头增加参数,返回指定类型结果
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="obj"></param>
        /// <param name="dicPair"></param>
        /// <returns></returns>
        public static T PostByHeader<T>(string url, object obj, Dictionary<string, string> dicPair)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (dicPair != null)
                {
                    foreach (var pair in dicPair)
                    {
                        request.Headers.Add(pair.Key, pair.Value);
                    }
                }
                var res = Post(request, obj);
                return JsonConvert.DeserializeObject<T>(res);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Post获取Token封装
        /// </summary>
        /// <typeparam name="T">返回Dto类</typeparam>
        /// <param name="url"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T PostGetToken<T>(string url, object obj = null)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ServicePoint.Expect100Continue = false;
                var StrRes = Post(request, obj);
                T result = JsonConvert.DeserializeObject<T>(StrRes);
                return result;
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion
    }
}
